package sample;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Alert;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ImageInput;
import javafx.scene.image.*;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.transform.Transform;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Random;
import java.util.zip.*;
import java.util.zip.ZipOutputStream;

import static com.sun.deploy.cache.Cache.copyFile;

public class BaseTool {
    String color;
    private java.awt.Image maskImage;    //蒙版图片
    private java.awt.Image sourceImage;    //源图片


    public String changeToRGBA(String str) {

        String colorValue = null;
        if (str.length() > 7) {
            int[] colorVal = new int[4];
            String touMing = str.substring(1, 3);
            String redstr = str.substring(3, 5);
            String greenstr = str.substring(5, 7);
            String bluestr = str.substring(7, 9);
            //   System.out.println(touMing + " " + redstr + " " + greenstr + " " + bluestr);
            colorVal[0] = Integer.parseInt(touMing, 16);
            double alpha = colorVal[0];
            colorVal[1] = Integer.parseInt(redstr, 16);
            colorVal[2] = Integer.parseInt(greenstr, 16);
            colorVal[3] = Integer.parseInt(bluestr, 16);
            // System.out.println("十进制的颜色值为：" + " " + alpha + " " + colorVal[1] + " " + colorVal[2] + " " + colorVal[3]);
            colorValue = Integer.toString(colorVal[1]) + "," + Integer.toString(colorVal[2]) + "," + Integer.toString(colorVal[3]) + "," + (double) (alpha / 255);
            //    System.out.println(colorValue);


            return colorValue;

        } else {
            int[] colorVal = new int[4];
            String redstr = str.substring(3, 5);
            String greenstr = str.substring(5, 7);
            String bluestr = str.substring(7, 9);
            colorVal[0] = Integer.parseInt(redstr, 16);
            colorVal[1] = Integer.parseInt(greenstr, 16);
            colorVal[2] = Integer.parseInt(bluestr, 16);
            colorValue = colorVal[0] + "," + colorVal[1] + "," + colorVal[2];
            return colorValue;
        }

    }

    public ImageView getImageView(String ImagePath, double width, double height, double number) throws MalformedURLException {
        File testFile = new File(ImagePath);
        Image image = new Image(testFile.toURI().toURL().toString());
        ImageView imageView = new ImageView(image);
        imageView.setFitHeight(height / number);
        imageView.setFitWidth(width / number);
        return imageView;
    }

    public String save(javafx.scene.Node view, String FileName, String Path) {

        Image image = view.snapshot(null, null);
        String path = Path + File.separator + "preview" + File.separator + FileName + ".png";

        File imafile = new File(path);
        if (imafile.exists()) {
            imafile.delete();
            System.out.println("截图删除了原有文件图片");
        }

        System.out.println("截图中的传送路径为" + path);
        try {
            if (ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", new File(path))) {
                removeBlackLine(path, FileName);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println("截图完成：" + df.format(System.currentTimeMillis()));
                return Path + File.separator + "preview";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }


    public String getXmlColor(String colorpath, String colorName) throws Exception {
        //  System.out.println("xml目录为" + " " + colorpath);
        String colorValue = null;
        // String colorValue = "vivo_window_statusbar_bg_color";
        // System.out.println(colorValue);
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(colorpath));

        Element root = document.getRootElement();
        //输出根标签的名字
        //    System.out.println(root.getName());
        //String xpath ="[color@name='vivo_upslide_divider_background']";//查询属性type='ondDelete'的composite
        org.dom4j.Node node = root.selectSingleNode("color[@name='" + colorName + "']");
        //  System.out.println(node.getText());
        colorValue = node.getText();
        //  System.out.println(changeToTen(colorValue));
        return colorValue;

    }

    public int[] changeToRGB(String color) {
        if (color.length() > 7) {
            int[] colorVal = new int[4];
            String touMing = color.substring(1, 3);
            String redstr = color.substring(3, 5);
            String greenstr = color.substring(5, 7);
            String bluestr = color.substring(7, 9);
            colorVal[0] = Integer.parseInt(redstr, 16);
            colorVal[1] = Integer.parseInt(greenstr, 16);
            colorVal[2] = Integer.parseInt(bluestr, 16);
            colorVal[3] = Integer.parseInt(touMing, 16);
            return colorVal;

        } else {
            int[] colorVal = new int[3];
            String redstr = color.substring(3, 5);
            String greenstr = color.substring(5, 7);
            String bluestr = color.substring(7, 9);
            colorVal[0] = Integer.parseInt(redstr, 16);
            colorVal[1] = Integer.parseInt(greenstr, 16);
            colorVal[2] = Integer.parseInt(bluestr, 16);
            return colorVal;
        }

    }

    //判断颜色深浅
    public String checkedColor(String color) {
        int colorVal[] = changeToRGB(color);
        int red = colorVal[0], blue = colorVal[1], green = colorVal[2];
        String strLight = "light";
        String strDark = "dark";
        if (red * 0.299 + green * 0.578 + blue * 0.114 >= 192) { //浅色
            return strLight;
        } else {  //深色
            return strDark;
        }
    }

    //去除截图的黑边
    public void removeBlackLine(String path, String FileName) {
        System.out.println("去黑边中...." + " ");
        System.out.println("去黑边中的路径为" + path);

        try {
            ImageIcon imageIcon = new ImageIcon(path);
            BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight()
                    , BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
            g2D.drawImage(imageIcon.getImage(), 0, 0,
                    imageIcon.getImageObserver());
            //循环每一个像素点，改变像素点的Alpha值

            int x_min = bufferedImage.getMinX();
            int x_max = bufferedImage.getWidth();
            int y_min = bufferedImage.getMinY();
            int y_max = bufferedImage.getHeight();

            int[] rgb = new int[3];
            for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
                int pixel = bufferedImage.getRGB(x, y_min);
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                int a = (pixel & 0xff000000) >>> 24;
                pixel = pixel | 0xffffffff;//透明或偏向白色射为白色
                bufferedImage.setRGB(x, y_min, pixel);

                pixel = bufferedImage.getRGB(x, y_max - 1);
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                int a1 = (pixel & 0xff000000) >>> 24;
                pixel = pixel | 0xffffffff;//透明或偏向白色射为白色
                bufferedImage.setRGB(x, y_max - 1, pixel);
            }
            for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {
                int pixel = bufferedImage.getRGB(x_min, y);
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                int a = (pixel & 0xff000000) >>> 24;
                pixel = pixel | 0xffffffff;//透明或偏向白色射为白色
                bufferedImage.setRGB(x_min, y, pixel);

                pixel = bufferedImage.getRGB(x_max - 1, y);
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                int a1 = (pixel & 0xff000000) >>> 24;
                pixel = pixel | 0xffffffff;//透明或偏向白色射为白色
                bufferedImage.setRGB(x_max - 1, y, pixel);
            }
            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
            //生成图片为PNG

            ImageIO.write(bufferedImage, "png", new File(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //去除.9的黑边
    public static ImageView removeNineBlack(Canvas canvas, double pixelScale) {
        WritableImage writableImage = new WritableImage((int) Math.rint(pixelScale * canvas.getWidth()), (int) Math.rint(pixelScale * canvas.getHeight()));
        PixelWriter pw = writableImage.getPixelWriter();
        Color color = new Color(255, 255, 255, 0);
        for (int x = 0; x < canvas.getWidth(); x++) {
            pw.setArgb(x, 0, color.getRGB());
            pw.setArgb(x, (int)canvas.getHeight()-1, color.getRGB());
        }
        for(int y=0;y<canvas.getHeight();y++){
            pw.setArgb(0, y, color.getRGB());
            pw.setArgb((int)canvas.getWidth()-1, y, color.getRGB());

        }

        ImageView imageView = new ImageView(writableImage);
        return imageView;

    }

    //获得画布中的.9.png图片

    public ImageView getCanvasImage(String path, int realWidth, int realHeight, int hopeWidth, int hopeHeight, int proportion, double pixelScale, int removeFlag) throws MalformedURLException {

        File testFile = new File(path);
        Image imageSearchText = new Image(testFile.toURI().toURL().toString());

        FxNinePatch np = new FxNinePatch(imageSearchText);
        Canvas canvas = new Canvas();
        canvas.setWidth(hopeWidth);
        canvas.setHeight(hopeHeight);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        np.drawNinePatch(gc, 0, 0, hopeWidth, hopeHeight);

        WritableImage writableImage = new WritableImage((int) Math.rint(pixelScale * canvas.getWidth()), (int) Math.rint(pixelScale * canvas.getHeight()));
        SnapshotParameters spa = new SnapshotParameters();
        spa.setTransform(Transform.scale(pixelScale, pixelScale));

        ImageView imageView;

        WritableImage writableImage1 = canvas.snapshot(spa, writableImage);

        int x_max =(int) writableImage1.getWidth();
        int y_max = (int)writableImage1.getHeight();

        for (int x = 0; x < writableImage1.getWidth(); x++) {
            PixelWriter pw = writableImage.getPixelWriter();
            Color color = new Color(255, 255, 255, 0);
            pw.setArgb((int) x, 0, color.getRGB());
            pw.setArgb((int) x, (int)y_max-1, color.getRGB());

        }

        for (int y = 0; y < writableImage1.getHeight(); y++) {
            PixelWriter pw = writableImage.getPixelWriter();
            Color color = new Color(255, 255, 255, 0);
            pw.setArgb((int) 0, y, color.getRGB());
            pw.setArgb((int) x_max-1, (int)y, color.getRGB());

        }

        imageView = new ImageView( canvas.snapshot(spa, writableImage));
        imageView.setFitWidth(hopeWidth / proportion);
        imageView.setPreserveRatio(true);

        return imageView;
    }

    public Canvas getNineCanvas(String path, int realWidth, int realHeight, int scaleWidth, int scaleHeight, int proportion, int buttomFalg) throws MalformedURLException {

        if (proportion == 1) {
            File testFile = new File(path);
            Image image = new Image(testFile.toURI().toURL().toString());
            FxNinePatch np = new FxNinePatch(image);
            Canvas canvas = new Canvas(scaleWidth, scaleHeight);
            GraphicsContext gc = canvas.getGraphicsContext2D();
            np.drawNinePatch(gc, 0, 0, scaleWidth, realHeight);
            return canvas;

        } else {
            File testFile = new File(path);
            Image image = new Image(testFile.toURI().toURL().toString());
            FxNinePatch np = new FxNinePatch(image);
            Canvas canvas = new Canvas(scaleWidth, realHeight);
            GraphicsContext gc = canvas.getGraphicsContext2D();
            gc.scale(480d / 1080d, 480d / 1080d);
            if (buttomFalg == 0) {
                np.drawNinePatch(gc, 0, 0, (int) (scaleWidth / (proportion * (480d / 1080d))), realHeight);
            } else {
                np.drawNinePatch(gc, 0, 0, (int) scaleWidth, realHeight);
            }

            return canvas;

        }

    }

    public Canvas getNinePatchCanvas(String path, int realWidth, int realHeight, int scaleWidth, int scaleHeight, int proportion, int buttomFalg) throws MalformedURLException {

        if (proportion == 1) {
            File testFile = new File(path);
            Image image = new Image(testFile.toURI().toURL().toString());
            FxNinePatch np = new FxNinePatch(image);
            Canvas canvas = new Canvas(scaleWidth, scaleHeight);
            GraphicsContext gc = canvas.getGraphicsContext2D();
            np.drawNinePatch(gc, 0, 0, scaleWidth, realHeight);
            return canvas;

        } else {
            File testFile = new File(path);
            Image image = new Image(testFile.toURI().toURL().toString());
            FxNinePatch np = new FxNinePatch(image);
            Canvas canvas = new Canvas(scaleWidth, realHeight);
            GraphicsContext gc = canvas.getGraphicsContext2D();
            gc.scale(360d / 1080d, 360d / 1080d);
            np.drawNinePatch(gc, 0, 0, scaleWidth, realHeight);
            return canvas;

        }

    }

    public Canvas getCanvas(String path, int realWidth, int realHeight, int scaleWidth, int scaleHeight, int proportion, int buttomFalg) throws MalformedURLException {

        if (proportion == 1) {
            File testFile = new File(path);
            Image image = new Image(testFile.toURI().toURL().toString());
            FxNinePatch np = new FxNinePatch(image);
            Canvas canvas = new Canvas(scaleWidth, scaleHeight);
            GraphicsContext gc = canvas.getGraphicsContext2D();
            np.drawNinePatch(gc, 0, 0, scaleWidth, realHeight);
            return canvas;

        } else {
            File testFile = new File(path);
            Image image = new Image(testFile.toURI().toURL().toString());
            FxNinePatch np = new FxNinePatch(image);
            Canvas canvas = new Canvas(scaleWidth, realHeight);
            GraphicsContext gc = canvas.getGraphicsContext2D();
            gc.scale(480d / 1080d, 360d / 1080d);
            np.drawNinePatch(gc, 0, 0, (int) (scaleWidth / (proportion * (480 / 1080d))), (realHeight));
            return canvas;

        }

    }

    //两张图片混合
    public ImageView mixPic(String sourcePicPath, String mixPicPath, int width, int height, int proportion) throws Exception {
        File mixFile = new File(mixPicPath);
        BufferedImage Mix_bufferedImage = ImageIO.read(mixFile);
        File sourceFile = new File(sourcePicPath);
        BufferedImage source_bufferedImage = ImageIO.read(sourceFile);

        for (int x = Mix_bufferedImage.getMinX(); x < Mix_bufferedImage.getWidth(); x++) {
            for (int y = Mix_bufferedImage.getMinY(); y < Mix_bufferedImage.getHeight(); y++) {
                int rgb[] = new int[3];
                int pixel = Mix_bufferedImage.getRGB(x, y); // 下面三行代码将一个数字转换为RGB数字
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                int alpha = pixel >> 24;
                 /*  System.out.println("x=" + x + ",y=" + y + ":(" + rgb[0] + ","
                           + rgb[1] + "," + rgb[2] + ")");*/
                if (rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0 && alpha != 0) {   //mix中的为黑
                    int RGB = source_bufferedImage.getRGB(x, y);
                    Mix_bufferedImage.setRGB(x, y, RGB);

                }
            }
        }
        // ImageIO.write(Mix_bufferedImage, "png", new File("E:\\Mix.png"));

        WritableImage wr = null;
        if (Mix_bufferedImage != null) {
            wr = new WritableImage(Mix_bufferedImage.getWidth(), Mix_bufferedImage.getHeight());
            PixelWriter pw = wr.getPixelWriter();
            for (int x = 0; x < Mix_bufferedImage.getWidth(); x++) {
                for (int y = 0; y < Mix_bufferedImage.getHeight(); y++) {
                    pw.setArgb(x, y, Mix_bufferedImage.getRGB(x, y));
                }
            }
        }
        ImageView imView = new ImageView(wr);
        imView.setFitWidth(width / proportion);
        imView.setFitHeight(height / proportion);
        return imView;

    }



    //移动文件夹
    public static void copyFolder(String oldPath, String newPath) {
        try {
            // 如果文件夹不存在，则建立新文件夹
            (new File(newPath)).mkdirs();
            // 读取整个文件夹的内容到file字符串数组，下面设置一个游标i，不停地向下移开始读这个数组
            File filelist = new File(oldPath);
            String[] file = filelist.list();
            // 要注意，这个temp仅仅是一个临时文件指针
            // 整个程序并没有创建临时文件
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                // 如果oldPath以路径分隔符/或者\结尾，那么则oldPath/文件名就可以了
                // 否则要自己oldPath后面补个路径分隔符再加文件名
                // 谁知道你传递过来的参数是f:/a还是f:/a/啊？
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                // 如果游标遇到文件
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    // 复制并且改名
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] bufferarray = new byte[1024 * 64];
                    int prereadlength;
                    while ((prereadlength = input.read(bufferarray)) != -1) {
                        output.write(bufferarray, 0, prereadlength);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                // 如果游标遇到文件夹
                if (temp.isDirectory()) {
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
        }

    }

    //移动文件
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(oldPath);
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("error  ");
            e.printStackTrace();
        }


    }


    //无状态栏背景图的深浅判断

    public String StatusBarColor(String path, int width, int height) throws IOException {
        File file = new File(path);
        BufferedImage Mix_bufferedImage = ImageIO.read(file);
        String strLight = "light";
        String strDark = "dark";
        int lightCount = 0;
        int darkCount = 0;

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int rgb[] = new int[3];
                int pixel = Mix_bufferedImage.getRGB(x, y); // 下面三行代码将一个数字转换为RGB数字
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                int alpha = pixel >> 24;
                 /*  System.out.println("x=" + x + ",y=" + y + ":(" + rgb[0] + ","
                           + rgb[1] + "," + rgb[2] + ")");*/
                if (rgb[0] * 0.299 + rgb[1] * 0.578 + rgb[2] * 0.114 >= 192) { //浅色
                    lightCount++;
                } else {  //深色
                    darkCount++;
                }

            }
        }
        System.out.println("lightCount" + " " + lightCount);
        System.out.println("darkCount" + " " + darkCount);
        if (lightCount > darkCount) {

            return strLight;
        } else {

            return strDark;
        }


    }

    //字体
    public Font getFont() throws Exception {
        Font f = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("C:\\Users\\Administrator\\Desktop\\主题素材"+File.separator+"Droid Sans Fallback.ttf"));
        return f;
    }



}
